package com.tomowork.dao.impl;

import com.tomowork.dao.IPermissionDAO;
import com.tomowork.entity.Permission;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
@Repository
public class PermissionDAOImpl implements IPermissionDAO {
    @PersistenceContext
    private EntityManager entityManager ;

    //根据用户id查询用户的权限

    /**
     * //user->role->permission,user_role,role-permission
     *1.查询用户对应的角色
     * SELECT ru.sys_role_id FROM RoleUser ru WHERE ru.sys_user_id=:userId ①
     * 2.根据角色id查询出用户对应的权限
     * SELECT rp.sys_permission_id  FROM RolePermission rp WHERE rp.sys_role_id in (①) ②
     * 3.根据权限id查找出所有的权限
     * FROM Permission p WHERE p.id in(②)
     *
     *由内向外扩展
     *
     *
     *
     * @return
     */

    @Override
    public List<Permission> selectPermissionListByUserId(String userId) {

        String jpql = "FROM Permission p WHERE p.id in( " +
                " SELECT   rp.permissionId FROM RolePermission rp WHERE rp.roleId in ( " +
                " SELECT ru.roleId FROM UserRole ru WHERE ru.userId=:userId) " +
                " )" ;
        Query query = entityManager.createQuery(jpql);
        List<Permission> permissionList = query.setParameter("userId", userId).getResultList();
        return permissionList;
    }
}
